import {COUPON_ENUM, BASE_URL, LOCATION_SETTING} from "./constant/index";
import {toast} from "./utils/tool";

function getCatch() {
    const user = wx.getStorageSync('user')
    return user || null
}

function getLocationSetting() {
    const value = (wx.getStorageSync(LOCATION_SETTING)) * 1
    return !!value
}

App({
    updateUserInfo() {
        return new Promise((resolve, reject) => {
            this.ajax({
                url: '/api/user/userinfo',
                success: res => {
                    if (res.code === 1) {
                        const {data} = res
                        this.setUserData(data)
                        return resolve(data)
                    }
                    reject(res)
                }
            })
        })
    },
    getUserInfo() {
        return new Promise((resolve, reject) => {
            wx.login({
                success: ({code: wxCode}) => {
                    this.ajax({
                        url: '/api/index/login',
                        data: {code: wxCode},
                        success: resp => {
                            const {code, data} = resp
                            if (code === 1) {
                                wx.setStorageSync('user', data)
                                wx.setStorageSync('token', data.token);
                                this.globalData.userInfo = data
                                this.globalData.loginTime = Date.now()
                                return resolve(resp)
                            }
                            reject(resp)
                        },
                        fail: err => {
                            reject(err)
                        }
                    });
                }
            });
        })
    },
    onLaunch: function () {
        this.initDev()
        this.appUpdate()
    },
    appUpdate() {
        const updateManager = wx.getUpdateManager()
        updateManager.onUpdateReady(() => {
            wx.showModal({
                title: '更新提示',
                content: '新版本已经准备好，是否重启应用？',
                success: ev => {
                    if (ev.cancel) return
                    // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                    updateManager.applyUpdate()
                }
            })
        })
    },
    setLocationSetting(value) {
        wx.setStorageSync(LOCATION_SETTING, value)
        this.globalData.hasLocation = !!value
    },
    checkLocationSetting() {
        return new Promise(resolve => {
            wx.getSetting({
                success: (res) => {
                    const {authSetting} = res
                    if (authSetting['scope.userLocation']) {
                        this.setLocationSetting(1)
                        return resolve(true)
                    }
                    wx.showModal({
                        title: '您未开启地理位置授权',
                        content: '请开启定位权限',
                        success: res => {
                            if (res.cancel) {
                                this.setLocationSetting(0)
                                return resolve(false)
                            }
                            if (res.confirm) {
                                wx.openSetting({
                                    success: resp => {
                                        const {authSetting} = resp
                                        if (!authSetting['scope.userLocation']) {
                                            this.setLocationSetting(0)
                                            return resolve(false)
                                        }
                                        this.setLocationSetting(1)
                                        resolve(true)
                                    },
                                    fail: () => {
                                        this.setLocationSetting(0)
                                        resolve(false)
                                    }
                                })
                            }
                        }
                    })

                }
            })
        })
    },
    globalData: {
        hasLocation: getLocationSetting(),
        isDev: '',
        loading: false,
        hasLogin: false,
        showFlag: false,
        userInfo: getCatch(),
        firstStore: wx.getStorageSync('firststore') || '',
        payOption: [],
        couponData: {
            [COUPON_ENUM.COUPON]: [],
            [COUPON_ENUM.GROUP]: []
        },
        userData: {},
        roomList: [],
        firstData: {},
        shopList: [],
        systemInfo: {},
        loginTime: 0,
        shouldUpdate: true,
        logoUrl:"",
        changeStore: null
    },
    setLogoUrl(value){
        this.globalData.logoUrl = value
    },
    initDev() {
        const info = wx.getSystemInfoSync()
        const {brand} = info
        this.globalData.isDev = brand === "devtools"
        this.globalData.systemInfo = info
    },
    checkHasMobile() {
        const {userInfo} = this.globalData
        if (!userInfo) return toast({title: '请先绑定手机号', time: 1500}, () => {
            wx.navigateTo({url: "/pages/login/login"})
        })
        const {mobile} = userInfo
        if (!!mobile) return true
        return toast({title: '请先绑定手机号', time: 1500}, () => {
            wx.navigateTo({url: "/pages/login/login"})
        })
    },

    getShopList() {
        return this.globalData.shopList
    },
    setShopList(data = []) {
        const result = []
        data.forEach((item, index) => {
            item = item.map(good => ({...good, index}))
            result.push(...item)
        })
        this.globalData.shopList = result
    },
    getFirst() {
        return this.globalData.firstStore
    },
    setFirst(data) {
        this.globalData.firstStore = {...data}
        wx.setStorageSync('firststore', data)
    },
    getRoomList() {
        return this.globalData.roomList
    },
    setRoomList(data) {
        if (!data || !data.length) return this.globalData.roomList.splice(0, this.globalData.roomList.length)
        this.globalData.roomList.splice(0, this.globalData.roomList.length, ...data)
    },
    setUserData(data) {
        this.globalData.userData = {...data}
        this.globalData.userInfo = {...data}
        wx.setStorageSync('user', data)
    },
    getUserData() {
        return this.globalData.userData
    },

    async initCouponData() {
        const coupon = await this.getCouponData(COUPON_ENUM.COUPON)
        // const group = await this.getCouponData(COUPON_ENUM.GROUP)
        return {
            coupon,
            couponLen: coupon.length,
        }
    },

    formatDate(time, showHour = false) {
        const date = new Date(time * 1000)
        const [year, month, day] = [date.getFullYear(), date.getMonth() + 1, date.getDate()]
        const res = `${year}-${month < 10 ? '0' + month : month}-${day >= 10 ? day : '0' + day}`
        if (!showHour) return res;
        const [hour, minutes] = [date.getHours(), date.getMinutes()]
        return `${res} ${hour < 10 ? '0' + hour : hour}:${minutes < 10 ? '0' + minutes : minutes}`
    },
    openShare() {
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
    },
    getCouponData(type) {
        return new Promise(resolve => {
            const url = {
                [COUPON_ENUM.COUPON]: '/api/user/coupons',
                [COUPON_ENUM.GROUP]: "/api/coupon/couponlist",
            }
            this.ajax({
                url: url[type],
                success: resp => {
                    const {code, data, msg} = resp
                    if (code !== 1) {
                        toast({title: msg})
                        return resolve([])
                    }
                    const {data:list} =data
                    if (!!list && list.length) {
                        this.globalData.couponData[type] = [...list]
                        resolve(list)
                    }
                }
            })
        })
    },
    // appid wxf124a40e49949016
    api_url: BASE_URL,
    // api_url: 'https://sanju.xinyunweb.com',
    // 开锁域名
    unlocking: 'http://ops.huohetech.com',
    ajax: function (o, show) {
        if (show) {
            wx.showLoading({
                mask: true,
                title: '正在加载...'
            });
        }
        var data = o.data || {};
        data.token = wx.getStorageSync('token') || '';
        wx.request({
            url: this.api_url + o.url,
            data: data,
            method: o.method || 'POST',
            header: o.header || {
                // 请求头
                'content-type': 'application/json',
            },
            success: function (res) {
                if (show) {
                    wx.hideLoading();
                }
                if (res && res.data && res.data.code !== undefined) {
                    if (res.data.code == -1) {
                        wx.showToast({
                            title: '未登录或登陆已失效',
                            icon: 'none'
                        });
                        return false;
                    }
                    if (o.success) o.success(res.data);
                } else {
                    wx.showToast({
                        title: '请求错误',
                        icon: 'none'
                    });
                }
            },
            fail: function (res) {
                if (show) {
                    wx.hideLoading();
                }
                wx.showToast({
                    title: '请求错误',
                    icon: 'none'
                });
            }
        })
    },
})
